<template>
  <view class="recommend-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input" @click="goToSearch">
        <u-icon name="search" size="18" color="#999"></u-icon>
        <text class="search-placeholder">搜索商品...</text>
      </view>
    </view>
    
    <!-- 分类标签 -->
    <view class="category-tabs">
      <scroll-view class="tabs-scroll" scroll-x>
        <view class="tabs-list">
          <view 
            v-for="(category, index) in categories" 
            :key="index"
            class="tab-item"
            :class="{ active: currentCategory === category.id }"
            @click="switchCategory(category.id)"
          >
            <text class="tab-text">{{ category.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view class="filter-item" @click="showSortOptions">
        <text class="filter-text">{{ getSortText() }}</text>
        <u-icon name="arrow-down" size="12" color="#666"></u-icon>
      </view>
      <view class="filter-item" @click="showPriceFilter">
        <text class="filter-text">价格</text>
        <u-icon name="arrow-down" size="12" color="#666"></u-icon>
      </view>
      <view class="filter-item" @click="showBrandFilter">
        <text class="filter-text">品牌</text>
        <u-icon name="arrow-down" size="12" color="#666"></u-icon>
      </view>
      <view class="filter-item" @click="toggleViewMode">
        <u-icon :name="viewMode === 'list' ? 'grid' : 'list'" size="16" color="#666"></u-icon>
      </view>
    </view>
    
    <!-- 商品列表 -->
    <scroll-view 
      class="product-list" 
      scroll-y 
      @scrolltolower="loadMore"
      @refresherrefresh="onRefresh"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
    >
      <view 
        v-for="(product, index) in productList" 
        :key="product.id"
        class="product-item"
        @click="viewProduct(product)"
      >
        <image class="product-image" :src="product.imageUrl" mode="aspectFill"></image>
        <view class="product-info">
          <text class="product-title">{{ product.title }}</text>
          <text class="product-desc">{{ product.description }}</text>
          <view class="product-tags">
            <text 
              v-for="(tag, idx) in product.tags" 
              :key="idx"
              class="product-tag"
            >
              {{ tag }}
            </text>
          </view>
          <view class="product-meta">
            <view class="price-info">
              <text class="current-price">¥{{ product.currentPrice }}</text>
              <text v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</text>
            </view>
            <view class="product-stats">
              <text class="sales-count">已售{{ formatCount(product.salesCount) }}</text>
              <text class="rating">{{ product.rating }}分</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="loading" class="loading-more">
        <u-loading-icon></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 没有更多 -->
      <view v-if="noMore" class="no-more">
        <text class="no-more-text">没有更多商品了</text>
      </view>
    </scroll-view>
    
    <!-- 排序选项弹窗 -->
    <u-popup 
      v-model="showSort" 
      mode="bottom" 
      height="auto"
      border-radius="20"
      closeable
    >
      <view class="sort-popup">
        <view class="popup-header">
          <text class="popup-title">排序方式</text>
        </view>
        <view class="sort-options">
          <view 
            v-for="(option, index) in sortOptions" 
            :key="index"
            class="sort-option"
            :class="{ active: currentSort === option.value }"
            @click="selectSort(option.value)"
          >
            <text class="option-text">{{ option.label }}</text>
            <u-icon v-if="currentSort === option.value" name="checkmark" size="16" color="#1890ff"></u-icon>
          </view>
        </view>
      </view>
    </u-popup>
    
    <!-- 价格筛选弹窗 -->
    <u-popup 
      v-model="showPrice" 
      mode="bottom" 
      height="auto"
      border-radius="20"
      closeable
    >
      <view class="price-popup">
        <view class="popup-header">
          <text class="popup-title">价格区间</text>
        </view>
        <view class="price-range">
          <input 
            class="price-input" 
            v-model="priceRange.min" 
            placeholder="最低价"
            type="number"
          />
          <text class="price-separator">-</text>
          <input 
            class="price-input" 
            v-model="priceRange.max" 
            placeholder="最高价"
            type="number"
          />
        </view>
        <view class="price-presets">
          <view 
            v-for="(preset, index) in pricePresets" 
            :key="index"
            class="price-preset"
            @click="selectPricePreset(preset)"
          >
            <text class="preset-text">{{ preset.label }}</text>
          </view>
        </view>
        <view class="popup-actions">
          <button class="action-btn secondary" @click="resetPriceFilter">重置</button>
          <button class="action-btn primary" @click="applyPriceFilter">确定</button>
        </view>
      </view>
    </u-popup>
    
    <!-- 品牌筛选弹窗 -->
    <u-popup 
      v-model="showBrand" 
      mode="bottom" 
      height="60%"
      border-radius="20"
      closeable
    >
      <view class="brand-popup">
        <view class="popup-header">
          <text class="popup-title">选择品牌</text>
        </view>
        <scroll-view class="brand-list" scroll-y>
          <view 
            v-for="(brand, index) in brandList" 
            :key="index"
            class="brand-item"
            :class="{ active: selectedBrands.includes(brand.id) }"
            @click="toggleBrand(brand.id)"
          >
            <text class="brand-name">{{ brand.name }}</text>
            <text class="brand-count">({{ brand.productCount }})</text>
            <u-icon v-if="selectedBrands.includes(brand.id)" name="checkmark" size="16" color="#1890ff"></u-icon>
          </view>
        </scroll-view>
        <view class="popup-actions">
          <button class="action-btn secondary" @click="resetBrandFilter">重置</button>
          <button class="action-btn primary" @click="applyBrandFilter">确定</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { get } from '@/utils/request';

// 商品接口
interface Product {
  id: string;
  title: string;
  description: string;
  imageUrl: string;
  currentPrice: number;
  originalPrice?: number;
  tags: string[];
  salesCount: number;
  rating: number;
  category: string;
}

// 分类接口
interface Category {
  id: string;
  name: string;
}

// 品牌接口
interface Brand {
  id: string;
  name: string;
  productCount: number;
}

// 价格预设接口
interface PricePreset {
  label: string;
  min: number;
  max: number;
}

// 排序选项接口
interface SortOption {
  label: string;
  value: string;
}

@Component
export default class RecommendPage extends Vue {
  // 数据属性
  currentCategory: string = 'all';
  productList: Product[] = [];
  
  loading: boolean = false;
  refreshing: boolean = false;
  noMore: boolean = false;
  page: number = 1;
  pageSize: number = 20;
  
  // 筛选相关
  showSort: boolean = false;
  showPrice: boolean = false;
  showBrand: boolean = false;
  
  currentSort: string = 'default';
  viewMode: string = 'list'; // list | grid
  
  priceRange: { min: string; max: string } = { min: '', max: '' };
  selectedBrands: string[] = [];
  
  brandList: Brand[] = [];
  
  sortOptions: SortOption[] = [
    { label: '综合排序', value: 'default' },
    { label: '销量优先', value: 'sales' },
    { label: '价格从低到高', value: 'price_asc' },
    { label: '价格从高到低', value: 'price_desc' },
    { label: '评分优先', value: 'rating' }
  ];
  
  pricePresets: PricePreset[] = [
    { label: '50元以下', min: 0, max: 50 },
    { label: '50-100元', min: 50, max: 100 },
    { label: '100-200元', min: 100, max: 200 },
    { label: '200-500元', min: 200, max: 500 },
    { label: '500元以上', min: 500, max: 9999 }
  ];
  
  categories: Category[] = [
    { id: 'all', name: '推荐' },
    { id: 'feeding', name: '喂养用品' },
    { id: 'clothing', name: '婴儿服装' },
    { id: 'toys', name: '玩具' },
    { id: 'care', name: '护理用品' },
    { id: 'safety', name: '安全用品' },
    { id: 'furniture', name: '婴儿家具' }
  ];
  
  // 生命周期
  onLoad() {
    this.loadProducts();
  }
  
  onShow() {
    this.refreshProducts();
  }
  
  onPullDownRefresh() {
    this.onRefresh();
  }
  
  onReachBottom() {
    this.loadMore();
  }
  
  // 方法
  
  /**
   * 加载商品
   */
  async loadProducts(isRefresh: boolean = false) {
    if (this.loading) return;
    
    this.loading = true;
    
    try {
      const response = await get('/products/recommend', {
        category: this.currentCategory,
        page: isRefresh ? 1 : this.page,
        pageSize: this.pageSize
      });
      
      const newProducts = response.data.products || [];
      
      if (isRefresh) {
        this.productList = newProducts;
        this.page = 1;
        this.noMore = false;
      } else {
        this.productList = [...this.productList, ...newProducts];
      }
      
      // 检查是否还有更多数据
      if (newProducts.length < this.pageSize) {
        this.noMore = true;
      } else {
        this.page++;
      }
      
    } catch (error) {
      console.error('加载商品失败:', error);
      
      // 使用模拟数据
      if (isRefresh || this.productList.length === 0) {
        this.productList = this.getMockProducts();
      }
      
      uni.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.loading = false;
      this.refreshing = false;
      uni.stopPullDownRefresh();
    }
  }
  
  /**
   * 刷新商品
   */
  async refreshProducts() {
    this.refreshing = true;
    await this.loadProducts(true);
  }
  
  /**
   * 下拉刷新
   */
  onRefresh() {
    this.refreshProducts();
  }
  
  /**
   * 加载更多
   */
  loadMore() {
    if (!this.noMore && !this.loading) {
      this.loadProducts();
    }
  }
  
  /**
   * 切换分类
   */
  switchCategory(categoryId: string) {
    if (this.currentCategory === categoryId) return;
    
    this.currentCategory = categoryId;
    this.page = 1;
    this.noMore = false;
    this.productList = [];
    
    this.loadProducts(true);
  }
  
  /**
   * 格式化数量
   */
  formatCount(count: number): string {
    if (count < 1000) {
      return count.toString();
    } else if (count < 10000) {
      return (count / 1000).toFixed(1) + 'k';
    } else {
      return (count / 10000).toFixed(1) + 'w';
    }
  }
  
  /**
   * 查看商品详情
   */
  viewProduct(product: Product) {
    uni.navigateTo({
      url: `/pages/product/detail?id=${product.id}`
    });
  }
  
  /**
   * 跳转到搜索页面
   */
  goToSearch() {
    uni.navigateTo({
      url: '/pages/search/search?type=product'
    });
  }
  
  /**
   * 显示排序选项
   */
  showSortOptions() {
    this.showSort = true;
  }
  
  /**
   * 显示价格筛选
   */
  showPriceFilter() {
    this.showPrice = true;
  }
  
  /**
   * 显示品牌筛选
   */
  showBrandFilter() {
    this.showBrand = true;
    this.loadBrands();
  }
  
  /**
   * 切换视图模式
   */
  toggleViewMode() {
    this.viewMode = this.viewMode === 'list' ? 'grid' : 'list';
  }
  
  /**
   * 获取排序文本
   */
  getSortText(): string {
    const option = this.sortOptions.find(opt => opt.value === this.currentSort);
    return option ? option.label : '综合排序';
  }
  
  /**
   * 选择排序方式
   */
  selectSort(sortValue: string) {
    this.currentSort = sortValue;
    this.showSort = false;
    this.refreshProducts();
  }
  
  /**
   * 选择价格预设
   */
  selectPricePreset(preset: PricePreset) {
    this.priceRange.min = preset.min.toString();
    this.priceRange.max = preset.max === 9999 ? '' : preset.max.toString();
  }
  
  /**
   * 应用价格筛选
   */
  applyPriceFilter() {
    this.showPrice = false;
    this.refreshProducts();
  }
  
  /**
   * 重置价格筛选
   */
  resetPriceFilter() {
    this.priceRange = { min: '', max: '' };
  }
  
  /**
   * 切换品牌选择
   */
  toggleBrand(brandId: string) {
    const index = this.selectedBrands.indexOf(brandId);
    if (index > -1) {
      this.selectedBrands.splice(index, 1);
    } else {
      this.selectedBrands.push(brandId);
    }
  }
  
  /**
   * 应用品牌筛选
   */
  applyBrandFilter() {
    this.showBrand = false;
    this.refreshProducts();
  }
  
  /**
   * 重置品牌筛选
   */
  resetBrandFilter() {
    this.selectedBrands = [];
  }
  
  /**
   * 加载品牌列表
   */
  async loadBrands() {
    if (this.brandList.length > 0) return;
    
    try {
      const response = await get('/products/brands', {
        category: this.currentCategory
      });
      
      this.brandList = response.data.brands || [];
    } catch (error) {
      console.error('加载品牌失败:', error);
      // 使用模拟数据
      this.brandList = this.getMockBrands();
    }
  }
  
  /**
   * 获取模拟品牌数据
   */
  getMockBrands(): Brand[] {
    return [
      { id: '1', name: '贝亲', productCount: 156 },
      { id: '2', name: '好孩子', productCount: 89 },
      { id: '3', name: '飞利浦新安怡', productCount: 67 },
      { id: '4', name: '美德乐', productCount: 45 },
      { id: '5', name: '小白熊', productCount: 78 }
    ];
  }
  
  /**
   * 获取模拟商品数据
   */
  getMockProducts(): Product[] {
    return [
      {
        id: '1',
        title: '婴儿奶瓶套装',
        description: '安全材质，防胀气设计，适合0-12个月宝宝',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20bottle%20set&image_size=square',
        currentPrice: 89.9,
        originalPrice: 129.9,
        tags: ['热销', '安全'],
        salesCount: 1250,
        rating: 4.8,
        category: 'feeding'
      },
      {
        id: '2',
        title: '婴儿连体衣5件套',
        description: '纯棉材质，柔软舒适，多种可爱图案',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20onesie%20set&image_size=square',
        currentPrice: 68.0,
        originalPrice: 98.0,
        tags: ['纯棉', '舒适'],
        salesCount: 890,
        rating: 4.7,
        category: 'clothing'
      },
      {
        id: '3',
        title: '婴儿安抚玩具',
        description: '柔软材质，安全无毒，帮助宝宝安睡',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20comfort%20toy&image_size=square',
        currentPrice: 45.0,
        tags: ['安抚', '安全'],
        salesCount: 567,
        rating: 4.9,
        category: 'toys'
      }
    ];
  }
}
</script>

<style lang="scss" scoped>
.recommend-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-bar {
  padding: 20rpx 30rpx;
  background-color: white;
  
  .search-input {
    display: flex;
    align-items: center;
    height: 70rpx;
    padding: 0 25rpx;
    background-color: #f8f8f8;
    border-radius: 35rpx;
    
    .search-placeholder {
      margin-left: 15rpx;
      font-size: 28rpx;
      color: #999;
    }
  }
}

.category-tabs {
  background-color: white;
  border-bottom: 1rpx solid #f0f0f0;
  
  .tabs-scroll {
    white-space: nowrap;
  }
  
  .tabs-list {
    display: flex;
    padding: 0 30rpx;
    
    .tab-item {
      flex-shrink: 0;
      padding: 25rpx 30rpx;
      margin-right: 10rpx;
      
      .tab-text {
        font-size: 28rpx;
        color: #666;
        transition: color 0.3s;
      }
      
      &.active {
        position: relative;
        
        .tab-text {
          color: #007aff;
          font-weight: 600;
        }
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 40rpx;
          height: 4rpx;
          background-color: #007aff;
          border-radius: 2rpx;
        }
      }
    }
  }
}

.product-list {
  flex: 1;
  padding: 20rpx;
}

.product-item {
  display: flex;
  background-color: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  
  .product-image {
    width: 200rpx;
    height: 200rpx;
    border-radius: 12rpx;
    margin-right: 20rpx;
    flex-shrink: 0;
  }
  
  .product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .product-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
      line-height: 1.4;
      margin-bottom: 10rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    
    .product-desc {
      font-size: 26rpx;
      color: #666;
      line-height: 1.4;
      margin-bottom: 15rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    
    .product-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 10rpx;
      margin-bottom: 15rpx;
      
      .product-tag {
        padding: 6rpx 12rpx;
        background-color: #fff2e8;
        color: #ff6b35;
        font-size: 22rpx;
        border-radius: 8rpx;
      }
    }
    
    .product-meta {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      
      .price-info {
        display: flex;
        align-items: baseline;
        
        .current-price {
          font-size: 32rpx;
          font-weight: 600;
          color: #ff4757;
          margin-right: 10rpx;
        }
        
        .original-price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
        }
      }
      
      .product-stats {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        
        .sales-count {
          font-size: 22rpx;
          color: #999;
          margin-bottom: 5rpx;
        }
        
        .rating {
          font-size: 22rpx;
          color: #ffd700;
        }
      }
    }
  }
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  
  .loading-text {
    margin-left: 15rpx;
    font-size: 26rpx;
    color: #999;
  }
}

.no-more {
  text-align: center;
  padding: 40rpx;
  
  .no-more-text {
    font-size: 26rpx;
    color: #999;
  }
}

// 筛选栏
.filter-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: white;
  border-bottom: 1rpx solid #f0f0f0;
  
  .filter-item {
    display: flex;
    align-items: center;
    margin-right: 40rpx;
    
    .filter-text {
      font-size: 26rpx;
      color: #333;
      margin-right: 8rpx;
    }
    
    &:last-child {
      margin-left: auto;
      margin-right: 0;
    }
  }
}

// 弹窗通用样式
.popup-header {
  text-align: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .popup-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.popup-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  
  .action-btn {
    flex: 1;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    border: none;
    
    &.secondary {
      background-color: #f8f9fa;
      color: #666;
    }
    
    &.primary {
      background-color: #1890ff;
      color: #fff;
    }
  }
}

// 排序弹窗
.sort-popup {
  background-color: #fff;
  
  .sort-options {
    padding: 0 30rpx 30rpx;
    
    .sort-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx 0;
      border-bottom: 1rpx solid #f8f9fa;
      
      &:last-child {
        border-bottom: none;
      }
      
      .option-text {
        font-size: 28rpx;
        color: #333;
      }
      
      &.active {
        .option-text {
          color: #1890ff;
        }
      }
    }
  }
}

// 价格筛选弹窗
.price-popup {
  background-color: #fff;
  
  .price-range {
    display: flex;
    align-items: center;
    padding: 30rpx;
    gap: 20rpx;
    
    .price-input {
      flex: 1;
      height: 70rpx;
      padding: 0 20rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
    
    .price-separator {
      font-size: 28rpx;
      color: #999;
    }
  }
  
  .price-presets {
    padding: 0 30rpx;
    display: flex;
    flex-wrap: wrap;
    gap: 15rpx;
    
    .price-preset {
      padding: 15rpx 25rpx;
      background-color: #f8f9fa;
      border-radius: 20rpx;
      
      .preset-text {
        font-size: 26rpx;
        color: #666;
      }
    }
  }
}

// 品牌筛选弹窗
.brand-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  
  .brand-list {
    flex: 1;
    padding: 0 30rpx;
    
    .brand-item {
      display: flex;
      align-items: center;
      padding: 30rpx 0;
      border-bottom: 1rpx solid #f8f9fa;
      
      .brand-name {
        font-size: 28rpx;
        color: #333;
        margin-right: 10rpx;
      }
      
      .brand-count {
        font-size: 24rpx;
        color: #999;
        margin-right: auto;
      }
      
      &.active {
        .brand-name {
          color: #1890ff;
        }
      }
    }
  }
}
</style>